package com.example.yc23.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yc23.demo.pojo.User;
import com.example.yc23.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 跳转到用户列表
     * @param key   查询关键字，可以是用户名或电话
     * @param pn    第几页
     * @param ps    每页显示几条
     *              return 到用户首页
     */
    @GetMapping("/index")
    public String index(String key, @RequestParam(defaultValue = "1") Integer pn, @RequestParam(defaultValue = "5") Integer ps, Model model){
        QueryWrapper wrapper=null;
        if (key!=null&&!"".equals(key)){
            wrapper=new QueryWrapper();
            wrapper.eq("username",key);
            wrapper.or();
            wrapper.eq("tel",key);

        }
        model.addAttribute("page",userService.page(new Page<>(pn,ps),wrapper));
        return "admin/user/index";
    }
    @GetMapping({"/lock/{uid}","/unlock/{uid}"})
    public String lock(@PathVariable Integer uid, HttpServletRequest request){
        Integer state=null;
        if (request.getRequestURI().contains("/lock"))
            state=0;
        if (request.getRequestURI().contains("/unlock"))
            state=1;
        UpdateWrapper wrapper=new UpdateWrapper();
        wrapper.eq("id",uid);
        wrapper.set("state",state);
        userService.update(wrapper);
        return "redirect:/admin/user/index";
    }
    @GetMapping({"/add","/update"})
    public String useradd(){
        return "admin/user/updateoradd";
    }
    @PostMapping("/updateoradd")
    public String updateoradd(User user,Model model){
        if (userService.saveOrUpdate(user)){
            return "redirect:/admin/user/index";//操作成功回到电影管理页面
        }else{
            model.addAttribute("user",user);
            model.addAttribute("msg","操作失败！");
            System.out.println(model.getAttribute("msg"));
            return "admin/user/updateoradd";//失败回到操作页面
        }
    }





}
